from ChartMaker.ChartMaker import ChartMaker
import webbrowser
import pymongo
import time


client = pymongo.MongoClient('localhost', 27017)
database = client['Weather']

db_region_list = database.list_collection_names()

info_dict = {}
for region in db_region_list:
    district_list = []
    for data in database[region].find():
        district_list.append(data['district'])
    info_dict[region] = district_list


if __name__ == '__main__':
    if len(db_region_list) == 0:
        print('当前数据库中没有城市数据, 请使用update.exe获取城市数据')
        print('即将退出程序')
        time.sleep(5)
    else:
        print('当前已获取信息的城市有:', end='')
        print(db_region_list)
        while True:
            while True:
                region = input("请输入查询的城市名称:")
                if region in db_region_list:
                    break
                print("城市名称有误, 请重试")
            choose = input('是否需要输入城市下级区名称(Y/N):')
            district = None
            if choose == 'Y':
                while True:
                    print(f'{region}市的下级区:', end='')
                    print(info_dict[region])
                    district = input("请输入查询的城市下级区名称:")
                    if district in info_dict[region]:
                        break
                    print("城市名称有误, 请重试")
            cm = ChartMaker()
            print('正在解析数据并绘制图表')
            chart = cm.get_charts(region, district)
            webbrowser.open(chart.render(f'{chart.page_title}.html'))
            print('已在浏览器中打开图表')
            choose = input('是否继续查询(Y/N):')
            if choose == 'N':
                break
        print('即将退出程序')
